<template>
  <!-- 因客户产品全面开放新页面，旧页面无用，所以该文件也没用了，暂时保留，如果引用页面删除，可以跟随删除 -->
  <!-- 改造为多行及筛选，未引入全局（避免样式影响）-->
  <div
    class="base-tabbar"
    :class="{
      'labelLittle': !labelExtend
    }"
    >

    <slot v-if="$slots.head"></slot>

    <div :class="{'base-tabbar-ghost': true, 'base-tabbar-highlight': prevBtnEnable}"></div>

    <div class="base-tabbar-scroll" ref="scroll" @wheel="tabScroll">
      <!-- 用于控制展开按钮的遮盖隐藏 -->
      <div class="right-shade"></div>
      <div 
        ref="list" 
        :class="{'base-tabbar-list': true, 'base-tabbar-transition': offsetTransition}" 
        :style="{transform: `translateX(${-offset}px)`}"
        @transitionend="tabTransitionEnd">
        <div 
          v-for="(t, index) in tabs"
          :key="`${t.component}_${index}`"
          class="base-tabbar-item"
          v-show="labelShowList.includes(t.key)"
          :class="{'base-tabbar-selected': t.component === value}"
          @click="selectTab(t)">
          <slot :name="`${t.component}__tab`">{{t.displayName}}</slot>
        </div>
      </div>
    </div>

    <el-popover
      placement="top-start"
      title="选择显示项"
      popper-class="right-tab-selector-popover"
      trigger="click">
      <el-button
        slot="reference"
        type="ghost"
        class="right-tab-selector">
        <i class="iconfont icon-gaojisousuo"></i>
      </el-button>
      <el-checkbox-group
        @change="labelShowListChange"
        class="right-tab-selector-group"
        v-model="labelShowList">
        <el-checkbox
          :key="label.key"
          :disabled="label.defaultShow"
          v-for="label in tabs"
          :label="label.key">
          {{label.displayName}}
        </el-checkbox>
      </el-checkbox-group>
    </el-popover>
    <i
      ref="moreLabelBtn"
      @click="labelExtend = !labelExtend"
      class="more-label-btn iconfont"
      :class="{
        'icon-fdn-select': !labelExtend,
        'icon-Icon_up': labelExtend,
      }">
    </i>

  </div>
</template>

<script>
import { t } from '@src/locales'
import _ from 'lodash';
import normalizeWheel from '@src/util/normalizeWheel'

export default {
  name: 'base-tabbar2',
  props: {
    tabs: {
      type: Array,
      default: () => ([])
    },
    api: {

    },
    value: String
  },
  data() {
    return {
      offset: 0,
      offsetTransition: false,
      nextBtnEnable: false,
      prevBtnEnable: false,
      showAll: false,
      isShowPopver: false,

      currTab: '',
      labelExtend: false,
      labelShowList: [],
      cardCacheList: []
    }
  },
  methods: {
    // 获取接口缓存的标签数据
    getCardCache() {
      this.api.getCardCache().then(res => {
        let list = []
        if (res.result) {
          list = res.result
        }
        this.cardCacheList = list
      }).catch(err => {
        console.log(err)
        this.cardCacheList = []
        this.$message.error(t('common.base.tip.getFilterConfigFail'))
      }).finally(() => {
        this.initLabelList()
      })
    },
    // 通过接口设置缓存的标签数据
    setCardCache() {
      this.api.setCardCache(this.labelShowList).then(res => {
        if (res.code !== 0) {
          this.$message.error(res.message)
        }
      }).catch(err => {
        console.log(err)
        this.$message.error(t('common.base.tip.setFilterConfigFail'))
      })
    },
    initLabelList() {
      this.labelShowList = this.tabs.filter(v => v.defaultShow || this.cardCacheList.includes(v.key)).map(v => v.key)
      this.prepard = true
    },
    // tab标签选择变更
    labelShowListChange(labelShowList) {
      if (!labelShowList.includes(this.currTab)) {
        this.tabs[0] && this.jump(this.tabs[0])
      }
      this.setCardCache()
    },


    selectTab(tab) {
      this.$emit('input', tab.component);
      this.currTab = tab.key
    },
    jump(tab){
      this.selectTab(tab);
      this.$nextTick(this.showSelectTab)
    },
    tabScroll(event){ 
      event.preventDefault();
      let scrollEl = this.$refs.scroll;
      let listEl = this.$refs.list;

      let scrollOffsetWidth = scrollEl.offsetWidth; // 外层容器的宽度
      let listOffsetWidth = listEl.offsetWidth; // tab list的宽度
      let maxOffset = listOffsetWidth - scrollOffsetWidth;
      // 无法滚动
      if(listOffsetWidth <= scrollOffsetWidth) return;

      let delta = normalizeWheel(event);
      let direction = delta.pixelX ? delta.pixelX : delta.pixelY;

      let offset = this.offset + direction;
      if(offset < 0) offset = 0;
      if(offset > maxOffset) offset = maxOffset;

      this.offset = offset;
      this.prevBtnEnable = this.offset > 0;
      this.nextBtnEnable = this.offset < maxOffset;
    },
    showSelectTab(){
      let scrollEl = this.$refs.scroll;
      let listEl = this.$refs.list;

      let scrollOffsetWidth = scrollEl.offsetWidth; // 外层容器的宽度
      let listOffsetWidth = listEl.offsetWidth; // tab list的宽度
      let maxOffset = listOffsetWidth - scrollOffsetWidth;
      if(maxOffset < 0){
        this.offset = 0;
        return;
      }

      let selectedEl = this.$refs.list.querySelector('.base-tabbar-selected');      
      let offset = selectedEl.offsetLeft < maxOffset ? selectedEl.offsetLeft : maxOffset;
      if(offset != this.offset){
        this.offsetTransition = true;
        this.prevBtnEnable = offset > 0;
        this.nextBtnEnable = offset < maxOffset;
        this.offset = offset;
      }
    },
    tabTransitionEnd(event){
      // 只处理tab list的tranform效果
      if(event.propertyName != 'transform' || !event.target.classList.contains('base-tabbar-list')) return;
      this.offsetTransition = false;
    },
    adjustTabs(tab){
      let scrollEl = this.$refs.scroll;
      let listEl = this.$refs.list;

      let scrollOffsetWidth = scrollEl.offsetWidth; // 外层容器的宽度
      let listOffsetWidth = listEl.offsetWidth; // tab list的宽度

      if(scrollOffsetWidth >= listOffsetWidth){ // 全部显示
        this.offset = 0;
        this.nextBtnEnable = false;
        this.prevBtnEnable = false;
        this.showAll = false;
        return;
      }

      let maxOffset = listOffsetWidth - scrollOffsetWidth;

      this.showAll = true;
      this.prevBtnEnable = this.offset > 0;
      this.nextBtnEnable = this.offset < maxOffset;
    },
    handler: _.debounce(function(tab){
      return this.adjustTabs(tab)
    }, 160)
  },
  mounted(){
    window.addEventListener('resize', this.handler);
    
    this.$nextTick(this.adjustTabs)

    this.getCardCache()
  },
  destroyed(){
    window.removeEventListener('resize', this.handler);
  },
  watch: {
    tabs: {
      deep: true,
      handler(){
        this.$nextTick(() => {
          this.adjustTabs();
          this.showSelectTab();
        })
      }
    }
  }
}
</script>

<style lang="scss">
.base-tabbar{
  margin: 0;
  height: auto;
  align-items: baseline;
  overflow: hidden;
  display: flex;
  flex-flow: row nowrap;
  position: relative;
  background: $bg-color-l2;
  &.labelLittle {
    max-height: 97px;
    overflow: hidden;
  }
}

.base-tabbar-scroll{
  flex: 1;
  position: relative;
  overflow: hidden;
  padding-right: 44px;
}

.base-tabbar-list{
  position: relative;
  bottom: 0;
}

.base-tabbar-item {
  display: inline-block;
  height: 48px;
  line-height: 48px;
  margin: 0 16px;
  font-size: 14px;
  color: #444;
  text-align: center;
  cursor: pointer;
  transition: color ease .15s;
  background: $bg-color-l2;
  font-weight: normal;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: middle;
  padding: 0;
  min-width: auto;
  
  i.iconfont{
    font-size: 14px;
    margin: 5px;
  }
}

.base-tabbar-item:hover,
.base-tabbar-item.base-tabbar-selected {
  color: $color-primary;
  border-bottom: 2px solid $color-primary;
}

.base-tabbar-transition{
  transition: transform linear .3s;
}

.base-tabbar-all{
  outline: none;
  width: 50px;
  height: 50px;
  margin: 0;
  background: $bg-color-l2;
  color: #444;
  border:none;
  border-bottom: 2px solid $color-regular;
  padding: 0 0 2px 0;
  position: relative;

  // &:hover{
  //   background: #CFEAE9 !important;
  //   color: #55B7B4;
  // }

  i{
    display: block;
  }

  &.base-tabbar-rotate i{
    transform: rotate(180deg);
  }
}

.base-tabbar-all.base-tabbar-highlight{
  box-shadow: -2px 0 4px rgba(0, 0, 0, .125);
}

.base-tabbar-ghost{
  position: absolute;
  left: -4px;
  top: 0;
  bottom: 0;
  background: $color-regular;
  width: 4px;
  z-index: 9;
}

.base-tabbar-ghost.base-tabbar-highlight{
  box-shadow: 2px 0 4px rgba(0, 0, 0, .125);
}


.theme-default .right-tab-selector-popover {
  padding: 0;
  min-width: 198px;
  max-width: 331px;
  .el-popover__title {
    padding: 0 12px;
    height: 38px;
    line-height: 38px;
    background: #F5F5F5;
    color: rgba(0, 0, 0, 0.65);
    margin-bottom: 0;
  }
  &>.popper__arrow:after {
    border-bottom-color: #f5f5f5;
  }
}
.theme-default .right-tab-selector-group {
  max-height: 259px;
  overflow: auto;
  padding-top: 8px;
  .el-checkbox {
    width: fit-content;
    width: auto;
    display: flex;
    align-items: center;
    height: 32px;
    padding: 0 12px;
    margin: 0;
    .el-checkbox__input {
      line-height: 0;
    }
    .el-checkbox__label {
      text-overflow: ellipsis;
      overflow: hidden;
      color: rgba(0, 0, 0, 0.85);
      max-width: 290px;
    }
    &.is-checked {
      .el-checkbox__label {
        color: rgba(0, 0, 0, 0.85);
      }
    }
    &.is-disabled {
      .el-checkbox__inner {
        background-color: #fff !important;
        border-color: rgba(126, 134, 142, 0.16) !important;
      }
      .el-checkbox__label {
        color: #BFBFBF;
      }
    }
  }
}
</style>

<style lang="scss" scoped>
  .more-label-btn {
    position: absolute;
    right: 16px;
    bottom: 16px;
    z-index: 0;
    line-height: 1;
    color: #000;
  }
  ::v-deep .el-button.right-tab-selector {
    position: absolute;
    right: 16px;
    top: 10px;
    display: inline;
    padding: 0;
    min-width: auto;
    z-index: 10;
    width: 24px;
    height: 24px;
    &:hover,
    &:active,
    &:focus {
      background-color: #fff;
      border-color: $color-primary-light-6;  
    }
    i {
      font-size: 12px;
    }
  }
  .right-shade {
    position: absolute;
    right: 0;
    width: 44px;
    height: calc(192px - 100%);
    z-index: 1;
    background: #fafafa;
  }
</style>
